package com.beidasoft.web.util;


import com.alibaba.fastjson.JSONObject;
import com.beidasoft.web.model.system.UserToMenHu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author LiuJinYuan
 * @company 北大软件
 * @description: TODO Httpclient 工具类
 * @create 2022-03-21 14:52
 */
@Slf4j
public class HttpUtil {

    public static JSONObject sendPostByFormPost(String roleId, String url, UserToMenHu  userToMenHu, int reSend, String ssoToken) {
        JSONObject result = new JSONObject();
        result.put("code",201);
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.add("SSO-TOKEN", ssoToken);
        headers.add("Content-Type","application/x-www-form-urlencoded");
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("roleId",roleId);
         paramMap.add("id",userToMenHu.getId());
        paramMap.add("userName",userToMenHu.getUserName());
        paramMap.add("passWord",userToMenHu.getPassWord());
        paramMap.add("isEnabled",userToMenHu.getIsEnabled());
        paramMap.add("isRelevance",0);
        paramMap.add("secretLevel",userToMenHu.getSecretLevel());
        paramMap.add("nodeId",userToMenHu.getNodeId());
        paramMap.add("isLocked",userToMenHu.getIsLocked());
        paramMap.add("realName",userToMenHu.getRealName());
        org.springframework.http.HttpEntity httpEntity = new org.springframework.http.HttpEntity(paramMap, headers);
        ResponseEntity<com.alibaba.fastjson.JSONObject> jdPost = RestTemplateUtils.post(url, httpEntity, com.alibaba.fastjson.JSONObject.class);
        if (jdPost.getStatusCodeValue() == 200 && jdPost.getBody() != null) {
            //body中会有一个password密码，需要将密码获取到并处理到前端
            result.put("code",200);
            if (jdPost.getBody().get("data") != null) {
                result.put("password", jdPost.getBody().get("data").toString());
            }
        }
        return result;
    }

    public static JSONObject sendPostByPost(String url, String list, int reSend, String ssoToken) {
        JSONObject result = new JSONObject();
        result.put("code",201);
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.add("SSO-TOKEN", ssoToken);
        headers.add("Content-Type","application/x-www-form-urlencoded");
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("userName",list);
        org.springframework.http.HttpEntity httpEntity = new org.springframework.http.HttpEntity(paramMap, headers);
        ResponseEntity<com.alibaba.fastjson.JSONObject> jdPost = RestTemplateUtils.post(url, httpEntity, com.alibaba.fastjson.JSONObject.class);
        if (jdPost.getStatusCodeValue() == 200 && jdPost.getBody() != null) {
            result.put("code",200);
        }
        return result;
    }
    public static JSONObject sendPostDeleteByPost(String url, String ids, int reSend, String ssoToken) {
        JSONObject result = new JSONObject();
        result.put("code",201);
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.add("SSO-TOKEN", ssoToken);
        headers.add("Content-Type","application/x-www-form-urlencoded");
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("ids",ids);
        org.springframework.http.HttpEntity httpEntity = new org.springframework.http.HttpEntity(paramMap, headers);
        ResponseEntity<com.alibaba.fastjson.JSONObject> jdPost = RestTemplateUtils.post(url, httpEntity, com.alibaba.fastjson.JSONObject.class);
        if (jdPost.getStatusCodeValue() == 200 && jdPost.getBody() != null) {
            result.put("code",200);
        }
        return result;
    }

    public static String loadGetUrl(String methodUrl, Map<String, String> params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String line;
        StringBuilder result = new StringBuilder();
        try {
            Set<String> keySet = params.keySet();
            StringBuilder paramStr = new StringBuilder();
            keySet.forEach(key -> {
                paramStr.append(key).append("=").append(params.get(key)).append("&");
            });
            methodUrl = methodUrl + "?" + paramStr.substring(0, paramStr.length() - 1);
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setRequestMethod("GET");// 默认GET请求
            connection.connect();// 建立TCP连接
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));// 发送http请求
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty("line.separator"));// "\n"
                }
            }
        } catch (IOException e) {
            log.error(e.toString(),e);
        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                log.error(e.toString(),e);
            }
            if (connection != null)
                connection.disconnect();
        }
        return result.toString();
    }

    /**
     * 根据法律法规id获取法律法规版本id
     * @param url
     * @param params
     * @param header
     * @return
     * @throws Exception
     */
    public static String lawDoPost(String url, String params, Map header) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        for (Iterator iter = header.keySet().iterator(); iter.hasNext(); ) {
            String key = String.valueOf(iter.next());
            String value = String.valueOf(header.get(key));
            httpPost.setHeader(key, value);
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(20000)
                .setSocketTimeout(20000).setConnectTimeout(20000).build();
        httpPost.setConfig(requestConfig);

        StringEntity entity = new StringEntity(params, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
                return jsonString;
            } else {
                log.error("请求返回:"+state);
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static JSONObject sendPostByDeletePost(String url, String ids, int i, String ssoToken) {
        JSONObject result = new JSONObject();
        result.put("code",201);
        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.add("SSO-TOKEN", ssoToken);
        headers.add("Content-Type","application/x-www-form-urlencoded");
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("ids",ids);
        org.springframework.http.HttpEntity httpEntity = new org.springframework.http.HttpEntity(paramMap, headers);
        ResponseEntity<com.alibaba.fastjson.JSONObject> jdPost = RestTemplateUtils.post(url, httpEntity, com.alibaba.fastjson.JSONObject.class);
        if (jdPost.getStatusCodeValue() == 200 && jdPost.getBody() != null) {
            result.put("code",200);
        }
        return result;
    }
}
